import string, random, json
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import get_user_model, authenticate
from apps.system.models import VCode
from apps.member.diary.models import Diary
from .models import Member, MemberRecord

User = get_user_model()
jwt_payload_hander = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class MemberMobileSignSerializer(serializers.Serializer):

    def validate(self, attrs):
        mobile = self.initial_data.get('mobile')
        vcode = self.initial_data.get('vcode')
        user_info = json.loads(self.initial_data.get('userInfo'))
        if not mobile or not vcode:
            msg = '参数无效'
            raise serializers.ValidationError(msg)

        # 验证码验证
        VCode.verify(mobile, vcode, VCode.SIGN)
        user = User.objects.filter(username=mobile).first()

        if not user:
            """注册"""
            user = User.objects.create_user(username=mobile, nickname=user_info['nickName'], gender=user_info['gender'])
            Member.objects.create(user=user, city=user_info['city'], province=user_info['province'],
                                  country=user_info['country'],avatarUrl=user_info['avatarUrl'])
            MemberRecord.objects.create(content_object=user, user=user, operate=MemberRecord.SIGN, describe='第一次注册')

        payload = jwt_payload_hander(user)

        return {
            'token': jwt_encode_handler(payload),
            'user_id': user.id,
            'username': user.nickname
        }


class MemberLoginByPwdSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }
        # all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE
        if all(credentials):
            user = authenticate(**credentials)
            if user and user.is_active:
                payload = jwt_payload_hander(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'username': user.username
                }
        raise serializers.ValidationError('账号密码错误！')


class MemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = Member
        fields = '__all__'


class MemberObtainSerializer(serializers.ModelSerializer):
    name = serializers.CharField(read_only=True, source='user.name')
    gender = serializers.IntegerField(read_only=True, source='user.gender')

    class Meta:
        model = Member
        fields = '__all__'


class MemberInfoSerializer(serializers.ModelSerializer):
    # 前端返回用户信息
    username = serializers.CharField(source='user.username')
    nickname = serializers.CharField(source='user.nickname')
    gender = serializers.CharField(source='user.gender')

    class Meta:
        model = Member
        fields = ('username', 'nickname', 'gender', 'avatarUrl', 'level')


class CollectSerizlizer(serializers.ModelSerializer):
    # 我的日志收藏
    object = serializers.SerializerMethodField()

    def get_object(self, obj):
        # print(obj.content_object)
        return DiarySerializer(obj.content_object).data

    class Meta:
        model = MemberRecord
        fields = '__all__'


class BrowseSerizlizer(serializers.ModelSerializer):
    # 我的浏览记录
    object = serializers.SerializerMethodField()

    def get_object(self, obj):
        # print(obj.content_object)
        return DiarySerializer(obj.content_object).data

    class Meta:
        model = MemberRecord
        fields = '__all__'


class DiarySerializer(serializers.ModelSerializer):
    class Meta:
        model = Diary
        fields = '__all__'
